package net.ifilm.controller;

import net.ifilm.common.Constants;
import net.ifilm.common.IFilmException;
import net.ifilm.common.cache.ICache;
import net.ifilm.entity.*;
import net.ifilm.service.*;
import net.ifilm.utility.DateTimeUtil;
import net.ifilm.utility.PicCompressUtil;
import net.ifilm.utility.StringUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.io.FileSystemUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 *
 */
@Controller
public class FilmController {

    /**
     * 日志对象
     */
    private static Log log = LogFactory.getLog(FilmController.class);

    /**
     * 电影类型业务类
     */
    @Autowired
    private FilmTypeService filmTypeService;

    /**
     * 轮播电影业务
     */
    @Autowired
    private SlideFilmService slideFilmService;

    /**
     * 电影业务类
     */
    @Autowired
    private FilmService filmService;

    /**
     * 电影评分业务类
     */
    @Autowired
    private FilmScoreService filmScoreService;

    /**
     * 全局缓存
     */
    @Autowired
    private ICache<Object, Object> defaultCache;

    @Autowired
    private SiteApplyService siteApplyService;

    @Autowired
    private LeaveMessageService leaveMessageService;

    // ------------------------------------------------------------------------------------------------ public method

    /**
     * 播放电影的统一入口
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/playFilm")
    public String playFilm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int pathIndex = 0;
        int flag = 0;
        try {
            pathIndex = Integer.parseInt(request.getParameter("nextPlayPathIndex"));
            flag = Integer.parseInt(request.getParameter("flag"));
        } catch (NumberFormatException e) {
            // ignore
        }

        Film film = filmService.findFilmById(filmId);

        double avgScore = filmScoreService.findAvgScore(filmId);
        film.setScore(avgScore);

        // 若是剧集
        if (flag != 1) {
            int size = film.getFilmPathList().size();
            if (size > 3 ) pathIndex = size - 1;
        }

        request.setAttribute("pathIndex", pathIndex);
        request.setAttribute("film", film);
        return "/page/play.jsp";
    }

    /**
     * 根据不同的条件（如：最新更新、内地剧场、海外剧场、动作片、喜剧片等）分页查询电影列表
     * 对应请求路径"/"
     *
     * 对应首页搜索电影时
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "filmListByCondition")
    public String filmListByCondition1(HttpServletRequest request) throws IOException {
        // add 针对于搜索提交的查询需要将关键字入库
        String queryType = request.getParameter("queryType");
        if ("1".equals(queryType)) {
            updHotKeyword(request.getParameter("searchKey"));
        }

        String redirect = filmListByCondition(request);
        return redirect;
    }

    /**
     * 根据不同的条件（如：最新更新、内地剧场、海外剧场、动作片、喜剧片等）分页查询电影列表
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/page/filmListByCondition")
    public String filmListByCondition2(HttpServletRequest request) throws IOException {
        String redirect = filmListByCondition(request);
        return redirect;
    }

    /**
     * 电影打分
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/clickScore")
    public String clickScore(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        double score = Double.parseDouble(request.getParameter("score"));

        // 判断是否有用户登陆
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.CURRENT_USER);
        int userId = -1; // -1 旨为匿名
        if (user != null) userId = user.getUserId();

        FilmScore filmScore = new FilmScore();
        filmScore.setFilmId(filmId);
        filmScore.setScore(score);
        filmScore.setUserId(userId);
        filmScore.setCreateTime(DateTimeUtil.getCurrentDate());
        filmScoreService.addFilmScore(filmScore);
        String returnJson = null;

        double avgScore = filmScoreService.findAvgScore(filmId);
        int scoreCount = filmScoreService.findScoreCount(filmId);
        returnJson = "{\"status\":\"0\", \"score\":\"" + avgScore + "\", \"count\":\"" + scoreCount + "\"}";

        out.println(returnJson);
        out.close();
        return null;
    }



    /**
     * 分页电影评论列表
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/discussList")
    public String discussList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int currentPage = Integer.parseInt(request.getParameter("page"));

        // 查询总记录数
        int totalNum = filmService.findFilmDiscussCount(filmId);

        PageCount pageCount = new PageCount();
        pageCount.setCountPerPage(5);
        pageCount.setFilmId(filmId);
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);

        List<FilmDiscuss> discussList = filmService.findFilmDiscussSplit(pageCount);

        request.setAttribute("discussList", discussList);
        request.setAttribute("totalNum", totalNum);
        request.setAttribute("pageCount", pageCount);
        request.setAttribute("filmId", filmId);

        return "/page/common/discuss.jsp";
    }

    /**
     * 提交电影评论
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/submitDiscuss.html")
    public String submitDiscuss(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");

        int filmId = Integer.parseInt(request.getParameter("filmId"));
        String commentsmessage = request.getParameter("commentsmessage");
        commentsmessage = StringUtil.filterHTML(commentsmessage); // 过滤HTML特殊字符
        String imageCode = request.getParameter("imageCode");

        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute("verifyCode");
        PrintWriter out = response.getWriter();

        // 判断验证码是否正确
        if (!(verifyCode.equalsIgnoreCase(imageCode))) {
            out.println("<script>alert('验证码已经失效，请重新登陆！');history.back();</script>");
            out.close();
        } else {
            FilmDiscuss filmDiscuss = new FilmDiscuss();
            filmDiscuss.setUserId(-1); // 匿名
            filmDiscuss.setCreateTime(DateTimeUtil.getCurrentDate());
            filmDiscuss.setFilmId(filmId);
            filmDiscuss.setContent(commentsmessage);
            filmService.addDiscuss(filmDiscuss);
        }

        return "/page/discussList.html?filmId=" + filmId + "&page=1";
    }

    /**
     * 友情链接提交申请
     *
     * @param map
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/sys/applyAccessSite", method= RequestMethod.POST)
    public String applyAccessSite(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String siteName = request.getParameter("siteName");
        String siteDomain = request.getParameter("siteDomain");
        String siterMail = request.getParameter("siterMail");
        String imageCode = request.getParameter("imageCode");

        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute("verifyCode");

        StringBuffer message = new StringBuffer();
        if (!(verifyCode.equalsIgnoreCase(imageCode))) {
            message.append("验证码错误，请点击<a href='javascript:history.back();'>返回</a>重新输入！");
        } else {
            Map<String, Object> parameter = new HashMap<String, Object>();
            parameter.put("siteName", siteName);
            List<SiteApply> siteApplyList = siteApplyService.queryApplySite(parameter);
            if (siteApplyList.size() != 0) {
                message.append("您已经为[<b>").append(siteName).append("</b>]提交过申请，请勿重复提交，审核通过会邮件通知您，谢谢。");
            } else {
                SiteApply siteApply = new SiteApply();
                siteApply.setSiteName(siteName);
                siteApply.setSiteDomain(siteDomain);
                siteApply.setSiterMail(siterMail);
                siteApply.setApplyTime(new Date());
                siteApplyService.addSiteApply(siteApply);

                message.append(siteName).append("[<b>").append(siteDomain).append("</b>]站点接入申请已提交，结果会邮件通知您，谢谢。");
            }

            message.append("点击<a href='http://www.5ifilm.net'>返回</a>");
        }

        request.setAttribute("message", message.toString());
        return "apply.jsp";
    }

    /**
     * 增加一个新的电影条目信息
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/addFilm", method= RequestMethod.POST)
    public String addFilm(HttpServletRequest request, HttpServletResponse response) throws IOException {
		log.info("begin method addFilm");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

		/*
		 * 处理HTPP请求参数
		 */
		String filmName = StringUtil.trim(multipartRequest.getParameter("filmname"));			// 电影标题
		String filmTime = StringUtil.trim(multipartRequest.getParameter("filmTime"));			// 电影播放时长
		String showTime = StringUtil.trim(multipartRequest.getParameter("showtime"));			// 电影上映年份
		String relationTags = StringUtil.trim(multipartRequest.getParameter("tags"));			// 电影相关标签
		String filmIntroduce = StringUtil.trim(multipartRequest.getParameter("filmintroduce"));	// 电影简介
		String[] stars = multipartRequest.getParameterValues("stars");							// 电影主演数组
		String[] filmtypeIds = multipartRequest.getParameterValues("filmtypeId");				// 电影类型数组
        String[] netpaths = multipartRequest.getParameterValues("netpath");						// 电影网络路径数组
		int limit = Integer.parseInt(multipartRequest.getParameter("islimit"));					// 是否限制级影片
		int hot = Integer.parseInt(multipartRequest.getParameter("ishot"));						// 是否是热门影片
		int regionId = Integer.parseInt(multipartRequest.getParameter("regionId"));				// 电影发行区域
		MultipartFile imageFile = multipartRequest.getFile("filmImage");						// 电影海报图片
		MultipartFile slideImageFile = multipartRequest.getFile("slideImage");					// 轮播电影大海报图片


        // 处理电影标准海报上传
        String imagePath = storeImageFile(request, imageFile, "film", 
				Constants.DEFAULT_FILM_IMAGE_WIDTH, 
				Constants.DEFAULT_FILM_IMAGE_HEIGHT);
		if (log.isDebugEnabled()) {
			log.debug(imagePath + " upload and compress complate");
		}

        // 处理小幅电影海报
        // /Users/mac/myworkspace/workspace/5ifilm/target/5ifilm
        String mimagePath = PicCompressUtil.cutImage(request.getRealPath("/"), imagePath);

		
        /* 创建电影对象 */
        Film film = new Film();
        film.setHot(hot);
        film.setIslimit(limit);
        film.setTags(relationTags);
        film.setFilmName(filmName);
        film.setFilmTime(filmTime);
        film.setShowTime(showTime);
        film.setRegionId(regionId);
        film.setImagePath(imagePath);
        film.setMimagePath(mimagePath);
        film.setFilmIntroduce(filmIntroduce);
        film.setCreateTime(DateTimeUtil.getCurrentDate());
        film.setClear(StringUtil.clearFilm(netpaths[0]));
        int generateKey = filmService.addFilm(film);
        if (log.isDebugEnabled()) {
			film.setFilmId(generateKey);
			log.debug("store: " + film);
		}

        // 若存在轮播大图片
        if (slideImageFile != null) {
            SlideFilm slideFilm = new SlideFilm();
            slideFilm.setFilmId(generateKey);
            slideFilm.setCreateTime(DateTimeUtil.getCurrentDate());
            slideFilm.setPicturePath(storeImageFile(request, slideImageFile, "slide", 700, 286));
            slideFilm.setMinPicPath(storeImageFile(request, multipartRequest.getFile("filmImage"), "slide", 120, 49));
            slideFilmService.addSlideFilm(slideFilm);
        }

        // 处理电影主演数据
        Map<String, Object> parameter = new HashMap<String, Object>();
        List<Star> starList = new ArrayList<Star>();
        for (String starName : stars) {
            parameter.put("starName", StringUtil.trim(starName));
            starList = filmService.findStar(parameter);

            int starId = 0;
            switch (starList.size()) {
                case 0: // 数据库中没有此条主演纪录
                    Star star = new Star();
                    star.setStarName(starName);
                    starId = filmService.addStar(star);
                    break;
                case 1: // 数据库已经存在一个此主演纪录
                    starId = starList.get(0).getId();
                    break;
                default: // 数据库中存在多条相同的明星名称
                    if (log.isWarnEnabled()) {
                        log.warn("the same of starName for " + starName);
                    }
                    starId = starList.get(0).getId(); // 容错处理
                    break;
            }

            // 关联电影与明星之间的关系
            parameter.clear();
            parameter.put("filmid", generateKey);
            parameter.put("starid", starId);
            filmService.relFilmStar(parameter);
            if (log.isInfoEnabled()) {
                log.info("add relation starId " + starId + " with filmId " + generateKey);
            }
        }

        // 关联电影关系
        parameter.clear();
        for (String filmTypeId : filmtypeIds) {
            parameter.put("filmId", generateKey);
            parameter.put("filmTypeId", filmTypeId);
            filmService.relFilmType(parameter);
            if (log.isInfoEnabled()) {
                log.info("add relation filmTypeId " + filmTypeId + " with filmId " + generateKey);
            }
        }

        // 关联电影与网络路径之间的关系
        FilmPath filmPath = null;
        for (int i = 0; i < netpaths.length; i++) {
            filmPath = new FilmPath();
            filmPath.setFilmId(generateKey);
            filmPath.setOrderNum(i);
            filmPath.setNetPath(netpaths[i]);
            filmPath.setPlayerType(2); //TODO 动态判断路径是否是百度还是快播

            filmService.relfilmpath(filmPath);
            if (log.isInfoEnabled()) {
                log.info("add relation filmid " + generateKey + " with netpath " + netpaths[i]);
            }
        }

		log.info("end method addFilm");

        return "filmList.html?page=1";
    }

    /**
     * 根据电影ID批量删除电影纪录
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/batchDelFilm", method= RequestMethod.GET)
    public String batchDelFilm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filmIdList = request.getParameter("filmIdList");
        String imagePathList = request.getParameter("imagePathList");
        String currentPage = request.getParameter("currentPage");

        int filmId = 0;
        String[] idList = filmIdList.split(",");
        String[] imageList = imagePathList.split(",");
        for (int i = 0; i < filmIdList.length(); i++) {
            filmId = Integer.parseInt(idList[i]);

            // 根据电影ID删除此电影在数据库中数据及其关联的数据
            filmService.delFilmPath(filmId);
            filmService.delDiscuss(filmId);
            filmService.delSocre(filmId);
            filmService.delRelFilmStar(filmId);
            filmService.delRelFilmType(filmId);
            slideFilmService.delSlideFilmById(filmId);
            filmService.delFilm(filmId);
            if (log.isInfoEnabled()) {
                log.info("delete film " + filmId + " success");
            }

            // 删除此电影的外部资源
            File file = new File(request.getRealPath("/") + imageList[i]);
            if (file.exists() && file.isFile()) {
                FileUtils.forceDelete(file);

                if (log.isInfoEnabled()) {
                    log.info("delete file " + file + " success");
                }
            }
        }
        
        return "filmList.html?page=" + currentPage;
    }

    /**
     * 根据电影ID删除电影纪录
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/delFilm", method= RequestMethod.GET)
    public String delFilm(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        String currentPage = request.getParameter("page");

        // 根据电影ID删除此电影在数据库中数据及其关联的数据
        filmService.delFilmPath(filmId);
        filmService.delDiscuss(filmId);
        filmService.delSocre(filmId);
        filmService.delRelFilmStar(filmId);
        filmService.delRelFilmType(filmId);
        slideFilmService.delSlideFilmById(filmId);
        filmService.delFilm(filmId);
        if (log.isInfoEnabled()) {
            log.info("delete film " + filmId + " success");
        }

        // 删除此电影的外部资源
        String imagePath = request.getParameter("imagePath");
        File file = new File(request.getRealPath("/") + imagePath);
        if (file.exists() && file.isFile()) {
            FileUtils.forceDelete(file);

            if (log.isInfoEnabled()) {
                log.info("delete file " + file + " success");
            }
        }

        return "filmList.html?page=" + currentPage;
    }

    /**
     * 增加新的电影类型
     *
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping(value="/bg/system/addFilmType", method= RequestMethod.POST)
    public String addFilmType(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        String newFilmType = request.getParameter("newFilmType");

        String errorMessage = null;
        try {
            filmTypeService.addFilmType(newFilmType);
            return null;
        } catch (IFilmException e) {
            log.error("new film typename is exist");

            errorMessage = e.getErrorMessage();
        }

        out.println(errorMessage);
        out.close();
        return null;
    }

    /**
     * 更新电影类型名称
     *
     * @param request
     * @param response
     * @return
     * @throws java.io.IOException
     */
    @RequestMapping(value="/bg/system/updateTypeName", method= RequestMethod.GET)
    public String updateTypeName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        String typeName = URLDecoder.decode(request.getParameter("typeName"), "utf-8");
        int filmTypeId = Integer.parseInt(request.getParameter("filmTypeId"));
        String currentPage = request.getParameter("currentPage");

        int count = filmTypeService.findFilmTypeByName(typeName);
        if (count == 0) { // 不存在此类型名称
            FilmType filmType = new FilmType();
            filmType.setFilmTypeId(filmTypeId);
            filmType.setTypeName(typeName);

            filmTypeService.updTypeName(filmType);

        }

        out.println(count);
        out.close();
        return null;
    }

    /**
     * 查询所有电影类型
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/filmTypeList", method= RequestMethod.GET)
    public String filmTypeList(HttpServletRequest request) throws IOException {
        String page = request.getParameter("page");

        int currentPage = 1;
        if (page != null || !"".equals(page)) {
            try {
                currentPage = Integer.parseInt(page);
            } catch (NumberFormatException e) {
                log.warn(e.toString());
            }
        }

        // 查询总记录数
        int totalNum = filmTypeService.findFilmTypeCount();

        PageCount pageCount = new PageCount();
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);

        List<FilmType> filmTypes = filmTypeService.findSplitFilmType(pageCount);

        request.setAttribute("pageCount", pageCount);
        request.setAttribute("filmTypes", filmTypes);
        return "listFilmType.jsp";
    }

    /**
     * 查询单个电影明细
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/filmDetail", method= RequestMethod.GET)
    public String filmDetail(HttpServletRequest request) throws IOException {
        String filmId = request.getParameter("filmId");

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        List<Film> filmList = filmService.findFilm(parameter);

        request.setAttribute("film", filmList.get(0));
        return "filmDetail.jsp";
    }

    /**
     * 查询单个电影明细
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/testPlay", method= RequestMethod.GET)
    public String testPlay(HttpServletRequest request) throws IOException {
        String filmId = request.getParameter("filmId");

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        List<Film> filmList = filmService.findFilm(parameter);

        request.setAttribute("film", filmList.get(0));
        return "testPlay.jsp";
    }

    /**
     * 删除电影类型
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/delFilmType", method= RequestMethod.GET)
    public String delFilmType(HttpServletRequest request) throws IOException {
        String filmTypeIdList = request.getParameter("filmTypeIdList");
        String currentPage = request.getParameter("currentPage");

        String[] idList = filmTypeIdList.split(",");
        for (String filmTypeId : idList) {
            filmTypeService.delFilmTypeById(filmTypeId);
        }

        return "filmTypeList.html?page=" + currentPage;
    }



    /**
     * 根据电影类型ID删除电影类型
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/delFilmTypeById", method= RequestMethod.GET)
    public String delFilmTypeById(HttpServletRequest request) throws IOException {
        String filmTypeId = request.getParameter("filmTypeId");
        String currentPage = request.getParameter("currentPage");
        
        filmTypeService.delFilmTypeById(filmTypeId);


        return "filmTypeList.html?page=" + currentPage;
    }

    /**
     * 分页查询所有电影条目信息
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/filmList")
    public String filmList(HttpServletRequest request) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));
        String sortColumn = request.getParameter("sortColumn");

        // 查询总记录数
        int totalNum = filmService.findFilmCount(null);

        PageCount pageCount = new PageCount();
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);
        pageCount.setSortColumn(sortColumn);
        List<Film> filmList = filmService.findSplitFilm(pageCount);

        request.setAttribute("pageCount", pageCount);
        request.setAttribute("filmList", filmList);

        return "listFilm.jsp";
    }

    /**
     * 根据输入关键字分页查询电影列表
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/filmListByKey")
    public String filmListByKey(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        String searchKey = request.getParameter("searchInput");
        String page = request.getParameter("page");

        // 若搜索关键字为空则查询所有
        if (searchKey == null || "".equals(searchKey)) return "filmList.html?page=1";

        int currentPage = 1;
        if (page != null || !"".equals(page) || page != "null") {
            try {
                currentPage = Integer.parseInt(page);
            } catch (NumberFormatException e) {
                log.warn(e.toString());
            }
        }

        // 查询总记录数
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("searchKey", searchKey);
        int totalNum = filmService.findFilmCount(parameter);


        PageCount pageCount = new PageCount();
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);
        pageCount.setSearchKey(searchKey);
        List<Film> filmList = filmService.findSplitFilm(pageCount);

        request.setAttribute("pageCount", pageCount);
        request.setAttribute("filmList", filmList);
        return "listFilm.jsp";
    }

    /**
     * 检查电影名称是否已经存在
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/isExistFilmName")
    public String isExistFilmName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        String filmName = request.getParameter("filmName");
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmName", filmName);
        int count = filmService.findFilmCount(parameter);

        out.println(count);
        out.close();
        return null;
    }

    /**
     * 查询所有电影类型列表以XML数据格式返回
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/listFilmType", method= RequestMethod.GET)
    public String listFilmType(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        StringBuffer returnXML = new StringBuffer();
        returnXML.append("<?xml version=\"1.0\" encoding=\"utf-8\">");
        returnXML.append("<ROOT>");
        List<FilmType> filmTypeList = filmService.findFilmTypeList();
        for (FilmType filmType : filmTypeList) {
            returnXML.append("<param id=\"").append(filmType.getFilmTypeId()).append("\" typename=\"")
                    .append(filmType.getTypeName()).append("\"/>");
        }
        returnXML.append("</ROOT>");

        out.println(returnXML.toString());
        out.close();
        return null;
    }

    @RequestMapping(value="/bg/system/listSelectFilmType", method= RequestMethod.GET)
    public String listSelectFilmType(HttpServletResponse response, HttpServletRequest request) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        int filmId = Integer.parseInt(request.getParameter("filmId"));
        List<FilmType> filmTypes = filmTypeService.queryFilmTypeByFilmId(filmId);

        StringBuffer returnXML = new StringBuffer();
        returnXML.append("<?xml version=\"1.0\" encoding=\"utf-8\">");
        returnXML.append("<ROOT>");
        List<FilmType> filmTypeList = filmService.findFilmTypeList();
        for (FilmType filmType : filmTypeList) {
            returnXML.append("<param id=\"").append(filmType.getFilmTypeId()).append("\" typename=\"")
                    .append(filmType.getTypeName()).append("\" ");
                    for (FilmType currentType : filmTypes) {
                        if (currentType.getFilmTypeId() == filmType.getFilmTypeId()) {
                            returnXML.append("checked=\"0\"");
                        }
                    }
            returnXML.append(" />");
        }
        returnXML.append("</ROOT>");

        out.println(returnXML.toString());
        out.close();
        return null;
    }

    /**
     * 以XML数据结构返回电影上映时间列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/listShowTime", method= RequestMethod.GET)
    public String listShowTime(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        final int initYear = 2013;

        StringBuffer returnXML = new StringBuffer();
        returnXML.append("<?xml version=\"1.0\" encoding=\"utf-8\">");
        returnXML.append("<ROOT>");
        for(int i = 0; i < 23; i++) {
            returnXML.append("<param value=\"").append(initYear - i).append("\"/>");
        }
        returnXML.append("</ROOT>");

        out.println(returnXML.toString());
        out.close();
        return null;
    }

    /**
     * 查询所有电影发行区列表已XML数据返回
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/listFilmRegion", method= RequestMethod.GET)
    public String listFilmRegion(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        StringBuffer returnXML = new StringBuffer();
        returnXML.append("<?xml version=\"1.0\" encoding=\"utf-8\">");
        returnXML.append("<ROOT>");
        List<Region> regionList = filmService.findRegionList();
        for (Region region : regionList) {
            returnXML.append("<param id=\"").append(region.getRegionId()).append("\" regionname=\"")
                    .append(region.getRegionName()).append("\"/>");
        }
        returnXML.append("</ROOT>");

        out.println(returnXML.toString());
        out.close();
        return null;
    }

    /**
     * 根据名称或者关键字查询电影明星列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/starList", method= RequestMethod.POST)
    public String starList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        
        String searchKey = request.getParameter("searchKey");
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("searchKey", searchKey);
        List<Star> starList = filmService.findStar(parameter);

        StringBuffer returnXML = new StringBuffer();
        returnXML.append("<data>");
        for (Star star : starList) {
            returnXML.append("<item>").append(star.getStarName()).append("</item>");
        }
        returnXML.append("</data>");

        out.println(returnXML.toString());
        out.close();
        return null;
    }

    /**
     * 分页查询轮播电影列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/slideFilmList", method= RequestMethod.GET)
    public String slideFilmList(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));

        // 查询总记录数
        int totalNum = slideFilmService.findSlideFilmCount();

        PageCount pageCount = new PageCount();
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);
        List<SlideFilm> slideFilmList = slideFilmService.findSlideFilm(pageCount);

        request.setAttribute("pageCount", pageCount);
        request.setAttribute("slideFilmList", slideFilmList);
        return "listSildeFilm.jsp";
    }

    /**
     * 分页查询轮播电影列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/delSlideFilmById", method= RequestMethod.GET)
    public String delSlideFilmById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        slideFilmService.delSlideFilmById(filmId);
        return "slideFilmList.html?page=" + currentPage;
    }

    /**
     * 改变轮播电影生效状态
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/changeActiveFlag", method= RequestMethod.POST)
    public String changeActiveFlag(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int activeFlag = Integer.parseInt(request.getParameter("activeFlag"));
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        parameter.put("activeFlag", activeFlag);
        slideFilmService.updSlideFilmById(parameter);
        return null;
    }

    /**
     * 改变电影状态，activeFlag、isLimit、isHot、isClear
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/changeFilmStatus", method= RequestMethod.GET)
    public String changeFilmStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int activeFlag = Integer.parseInt(request.getParameter("activeFlag"));
        int isLimit = Integer.parseInt(request.getParameter("limit"));
        int isHot = Integer.parseInt(request.getParameter("hot"));
        int isClear = Integer.parseInt(request.getParameter("clear"));
        int regionId = Integer.parseInt(request.getParameter("regionId"));
        String showTime = request.getParameter("showTime");

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        parameter.put("activeFlag", activeFlag);
        parameter.put("isLimit", isLimit);
        parameter.put("isHot", isHot);
        parameter.put("isClear", isClear);
        parameter.put("showTime", showTime);
        parameter.put("regionId", regionId);
        filmService.updFilmStatus(parameter);
        return null;
    }

    /**
     * 分页显示热门标签列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/listHotMark", method= RequestMethod.GET)
    public String listHotMark(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return "listHotMark.jsp";
    }

    /**
     * 发行区列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/listRegion", method= RequestMethod.GET)
    public String listRegion(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<Region> regionList = (List<Region>) defaultCache.get("regionList");
        request.setAttribute("regionList", regionList);
        return "listRegion.jsp";
    }

    /**
     * 更新发行区域
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/updateRegion")
    public String updateRegion(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String value = request.getParameter("value");
        int id = Integer.parseInt(request.getParameter("id"));

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("regionId", id);
        parameter.put("regionName", value);
        filmService.updateRegionName(parameter);

        List<Region> regionList = (List<Region>) defaultCache.get("regionList");
        for (Region region : regionList) {
            if (region.getRegionId() == id) {
                region.setRegionName(value);
            }
        }

        if (log.isInfoEnabled()) {
            log.info("region id " + id + " regionName is updated");
        }

        return null;
    }

    /**
     * 明星列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/listStar", method= RequestMethod.GET)
    public String listStar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return "listStar.jsp";
    }

    /**
     * 用户留言列表
     *
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/leaveMessage", method= RequestMethod.GET)
    public String leaveMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));

        // 查询总记录数
        int totalNum = filmService.findLeaveMessageCount();

        PageCount pageCount = new PageCount();
        pageCount.setCountPerPage(10);
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);
        List<LeaveMessage> leaveMessageList = filmService.findLeaveMessage(pageCount);


        request.setAttribute("leaveMessageList", leaveMessageList);
        request.setAttribute("messageCount", totalNum);
        request.setAttribute("pageCount", pageCount);

        return "leaveMessage.jsp";
    }

    @RequestMapping(value="/bg/system/delLeaveMessage", method= RequestMethod.GET)
    public String delLeaveMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));
        int leaveMessageId = Integer.parseInt(request.getParameter("id"));

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("id", leaveMessageId);
        leaveMessageService.deleteLeaveMessage(parameter);

        return "leaveMessage.html?page=" + currentPage;
    }

    /**
     * 管理员后台登陆处理请求
     *
     * 管理员帐号密码使用静态字符串代替，管理员帐号默认为wangjun，密码为wj7790771
     *
     * @param request Http请求对性
     * @param response Http响应对象
     * @return 后台跳转路径
     * @throws IOException 可能抛出的IO一场
     */
    @RequestMapping(value="/bg/login", method= RequestMethod.POST)
    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("process administrator login request begin");

        // 设置响应消息头
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        // 获取用户提交参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String imageCode = request.getParameter("imageCode");

        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute("verifyCode");

        // 判断验证码是否正确
       if (!(verifyCode.equalsIgnoreCase(imageCode))) {
            log.warn("imageCode is invalid");
            out.println("<script>alert('验证码已经失效，请重新登陆！');history.back();</script>");
            out.close();
            return null;
        }

        PageCount pageCount = new PageCount();
        User user = new User();
        user.setAdmin(1);
        user.setNickName(username);
        user.setPassword(password);
        pageCount.setUser(user);
        List<User> userList = filmService.findUser(pageCount);
        if (userList == null || userList.size() == 0) {
            if (log.isErrorEnabled()) {
                log.error(username + " is not exist.");
            }

            out.println("<script>alert('用户不存在！');history.back();</script>");
            out.close();
            return null;
        }

        log.info("login success!");
        return "main.htm";
    }

    /**
     * 提交用户对网站内容
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/sys/submitLeaveMessage", method= RequestMethod.POST)
    public String submitLeaveMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        String commentsmessage = request.getParameter("commentsmessage");
        commentsmessage = StringUtil.filterHTML(commentsmessage); // 过滤特殊字符
        String imageCode = request.getParameter("imageCode");
        String currentPage = request.getParameter("currentPage");

        HttpSession session = request.getSession();
        String verifyCode = (String) session.getAttribute("verifyCode");
        PrintWriter out = response.getWriter();
        
        // 判断验证码是否正确
        if (!(verifyCode.equalsIgnoreCase(imageCode))) {
            log.warn("imageCode is invalid");
            out.println("<script>alert('验证码已经失效，请重新登陆！');history.back();</script>");
            out.close();
        } else {
            LeaveMessage leaveMessage = new LeaveMessage();
            leaveMessage.setMessage(commentsmessage);
            leaveMessage.setUserId(-1);
            int generateKey = filmService.addLeaveMessage(leaveMessage);
            if (log.isInfoEnabled()) {
                log.info("leavemessage " + generateKey + " add success");
            }
        }

        return "listLeaveMessage.html?page=" + currentPage;
    }

    /**
     * 列出用户留言列表
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/page/sys/listLeaveMessage")
    public String listLeaveMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));

        // 查询总记录数
        int totalNum = filmService.findLeaveMessageCount();

        PageCount pageCount = new PageCount();
        pageCount.setCountPerPage(5);
        pageCount.setTotalNum(totalNum);
        pageCount.setCurrentPage(currentPage);
        List<LeaveMessage> leaveMessageList = filmService.findLeaveMessage(pageCount);


        request.setAttribute("leaveMessageList", leaveMessageList);
        request.setAttribute("messageCount", totalNum);
        request.setAttribute("pageCount", pageCount);
        return "message.jsp";
    }

    /**
     * 模糊查询电影名称，用于电影名称的自动补全
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="autoFilmName", method= RequestMethod.POST)
    public String autoFilmName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        toggle(request, response);
        return null;
    }

    /**
     * 模糊查询电影名称，用于电影名称的自动补全
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value="/bg/system/autoFilmName", method= RequestMethod.POST)
    public String autoFilmName1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        toggle(request, response);
        return null;
    }
    
    @RequestMapping(value="/bg/system/delRelFilmStar")
    public String delRelFilmStar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int starId = Integer.parseInt(request.getParameter("starId"));
        
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        parameter.put("starId", starId);
        filmService.delRelFilmStar(parameter);
        return null;
    }

    @RequestMapping(value="/bg/system/delFilmTypeByFilmId")
    public String delFilmTypeByFilmId(HttpServletRequest request) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int filmTypeId = Integer.parseInt(request.getParameter("filmTypeId"));

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        parameter.put("filmTypeId", filmTypeId);

        filmTypeService.delFilmType(parameter);
        return null;
    }

    @RequestMapping(value="/bg/system/relFilmType")
    public String relFilmType(HttpServletRequest request) throws IOException {
        int filmId = Integer.parseInt(request.getParameter("filmId"));
        int filmTypeId = Integer.parseInt(request.getParameter("filmTypeId"));

        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("filmId", filmId);
        parameter.put("filmTypeId", filmTypeId);

        filmService.relFilmType(parameter);
        return null;
    }

    // ------------------------------------------------------------------------------------------ private method

	/**
	 * 执行图片上传和压缩
	 *
	 * @param request
	 * @param imageFile
	 * @param typeDir 
	 * @param width
	 * @param height
	 *
	 * @return 处理完的图片路径
	 */
    private String storeImageFile(HttpServletRequest request, MultipartFile imageFile, String typeDir,
                                  int width, int height) throws IOException {
        String uploadImageName = imageFile.getOriginalFilename();
        String basePath = request.getRealPath("/");
        
        StringBuffer uploadFileDir = new StringBuffer();
        uploadFileDir.append("/upload/").append(typeDir).append('/').append(DateTimeUtil.getDate()).append('/');
        File uploadDir = new File(basePath, uploadFileDir.toString());
        if (!uploadDir.exists()) uploadDir.mkdirs();

        // 写入磁盘
        File uploadFile = new File(basePath, uploadFileDir.toString() + uploadImageName);
        imageFile.transferTo(uploadFile);

        // 压缩图片
        String newImageFileName = System.currentTimeMillis() + "_" + uploadImageName;
        PicCompressUtil.compressPic(uploadFile, basePath+uploadFileDir, newImageFileName, width, height, false);
        uploadFile.delete();

        return uploadFileDir.toString() + newImageFileName;
    }

    private void toggle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();

        String filmName = request.getParameter("searchKey");
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("searchKey", filmName);
        List<Film> filmList = filmService.findFilm(parameter);

        StringBuffer returnXML = new StringBuffer();
        returnXML.append("<data>");
        for (Film film : filmList) {
            returnXML.append("<item>").append(film.getFilmName()).append("</item>");
        }
        returnXML.append("</data>");

        out.println(returnXML.toString());
        out.close();
    }

    private String filmListByCondition(HttpServletRequest request) throws IOException {
        int currentPage = Integer.parseInt(request.getParameter("page"));
        String filmTypeId = request.getParameter("filmTypeId");
        String regionId = request.getParameter("regionId");
        String sortColumn = request.getParameter("sortColumn");
        String sortColumnSecond = request.getParameter("sortColumnSecond");
        String showTime = request.getParameter("showTime");
        String starId = request.getParameter("starId");
        String type = request.getParameter("type");
        String level = request.getParameter("level");
        String searchKey = request.getParameter("searchKey");
        if (searchKey != null) {
            searchKey = URLDecoder.decode(searchKey, "UTF-8");
        }
        String tag = request.getParameter("tag");
        if (tag != null) {
            tag = URLDecoder.decode(tag, "UTF-8");
        }


        // 查询总记录数
        Map<String, Object> parameter = new HashMap<String, Object>();
        parameter.put("sortColumn", sortColumn);
        parameter.put("sortColumnSecond", sortColumnSecond);
        parameter.put("regionId", regionId);
        parameter.put("filmTypeId", filmTypeId);
        parameter.put("showTime", showTime);
        parameter.put("starId", starId);
        parameter.put("tag", tag);
        parameter.put("searchKey", searchKey);
        parameter.put("type", type);
        parameter.put("level", level);
        int totalNum = filmService.findFilmCount(parameter);

        PageCount pageCount = new PageCount();
        pageCount.setSortColumn(sortColumn);
        pageCount.setSortColumnSecond(sortColumnSecond);
        pageCount.setFilmTypeId(filmTypeId);
        pageCount.setRegionId(regionId);
        pageCount.setType(type);
        pageCount.setLevel(level);
        pageCount.setShowTime(showTime);
        pageCount.setStarId(starId);
        pageCount.setTag(tag);
        pageCount.setTotalNum(totalNum);
        pageCount.setCountPerPage(20);
        pageCount.setCurrentPage(currentPage);
        pageCount.setSearchKey(searchKey);
        List<Film> filmList = filmService.findSplitFilm(pageCount);

        request.setAttribute("parameter", parameter);
        request.setAttribute("pageCount", pageCount);
//        request.setAttribute("totalNum", totalNum);
        request.setAttribute("filmList", filmList);

        return "/page/video/video_list.jsp";
    }

    /**
     * 搜索时将用户输入的关键字入库
     *
     * @param keyword 关键字
     */
    private void updHotKeyword(String keyword) {
        HotKeyword hotKeyword = new HotKeyword();
        hotKeyword.setKeyword(keyword);

        HotKeyword keywordResult = filmService.queryHotKeyword(hotKeyword);
        if (keywordResult == null) {
            filmService.addHotKeyword(hotKeyword);

            if (log.isInfoEnabled()) {
                log.info("the keyword [" + keyword + "] has already store.");
            }
        } else {
            filmService.updateHotKeyword(keywordResult);

            if (log.isInfoEnabled()) {
                log.info("the keyword [" + keyword + "] has already updated.");
            }
        }



    }

} ///:~
